mergeInto(LibraryManager.library, {
    // 使用 Module 对象存储状态
    IndexedDB_Init: function (dbName, version, storesJson, initFinishCallback) {
        // 检查必要的全局对象是否可用
        if (typeof Module === 'undefined') {
            console.error('IndexedDBPlugin: Module object is not available.');
            return;
        }
        
        var _storesJson = storesJson ? UTF8ToString(storesJson) : null;

        // 初始化状态对象
        if (!Module.IndexedDBPlugin) {
            Module.IndexedDBPlugin = {
                instance: {},
                isSyncing: false, // 添加同步状态标志
                syncQueue: [],    // 同步队列
                
                _safeCallback: function (signature, callbackFunction) {
                    console.log('=== Signature:', signature);
                    console.log('=== Callback pointer:', callbackFunction);
                    console.log('=== Total arguments:', arguments.length);
                    console.log('=== WasmTable available:', typeof wasmTable !== 'undefined');
                
                    // 验证回调函数
                    if (typeof callbackFunction !== 'number' || callbackFunction === 0) {
                        console.error('传入的 callbackFunction 指针无效');
                        return;
                    }
                    
                    // 收集额外参数
                    var args = [];
                    for (var i = 2; i < arguments.length; i++) {
                        args.push(arguments[i]);
                    }
                    
                    try {
                        // 优先级1: Module.dynCall  
                        if (typeof Module !== 'undefined' && typeof Module.dynCall === 'function') {
                            Module.dynCall(signature, callbackFunction, args);
                            return;
                        }
                        
                        // 优先级2: wasmTable（最可靠）
                        if (typeof wasmTable !== 'undefined') {
                            if (callbackFunction < 0 || callbackFunction >= wasmTable.length) {
                                console.error('callbackFunction 指针超出边界:', callbackFunction, 'Table size:', wasmTable.length);
                                return;
                            }
                            var func = wasmTable.get(callbackFunction);
                            if (typeof func === 'function') {
                                func.apply(null, args);
                                return;
                            }
                        }
                        
                        // 优先级3: Module.asm
                        if (typeof Module !== 'undefined' && Module.asm) {
                            var dynCallFunc = Module.asm['dynCall_' + signature];
                            if (typeof dynCallFunc === 'function') {
                                // 构建参数数组：回调函数指针 + 额外参数
                                var allArgs = [callbackFunction].concat(args);
                                dynCallFunc.apply(null, allArgs);
                                return;
                            }
                        }
                        
                        console.error('All callback methods failed for signature:', signature);
                        
                    } catch (e) {
                        console.error('_safeCallback error:', e);
                    }
                },
                
                //js的字符串转成C#支持的类型
                _stringToC: function(str) {
                    var length = lengthBytesUTF8(str) + 1;
                    var buffer = _malloc(length);
                    stringToUTF8(str, buffer, length);
                    return buffer;
                },
                
                // 安全的回调方法
                _safeSyncFS: function(callback) {
                    var state = Module.IndexedDBPlugin;
                    
                    if (state.isSyncing) {
                        // 如果正在同步，将回调加入队列
                        if (callback) state.syncQueue.push(callback);
                        console.log("Sync already in progress, queuing request");
                        return;
                    }
                    
                    state.isSyncing = true;
                    
                    if (typeof FS !== 'undefined' && typeof FS.syncfs === 'function') {
                        FS.syncfs(false, function (err) {
                            state.isSyncing = false;
                            
                            if (err) {
                                console.error("SyncFS error:", err);
                            } else {
                                console.log("SyncFS completed successfully.");
                            }
                            
                            // 执行当前回调
                            if (callback && typeof callback === 'function') {
                                try {
                                    callback(err);
                                } catch (e) {
                                    console.error("Sync callback error:", e);
                                }
                            }
                            
                            // 处理队列中的下一个请求
                            if (state.syncQueue.length > 0) {
                                var nextCallback = state.syncQueue.shift();
                                setTimeout(function() {
                                    state._safeSyncFS(nextCallback);
                                }, 100); // 添加短暂延迟
                            }
                        });
                    } else {
                        state.isSyncing = false;
                        if (callback) callback(new Error("FS.syncfs not available"));
                    }
                },
                
                _isInt: function(str) {
                    return /^-?\d+$/.test(str);
                }
            }
        }

        var _dbName = UTF8ToString(dbName);
        var state = Module.IndexedDBPlugin;
        if(!state.instance.hasOwnProperty(_dbName)){
            state.instance[_dbName] = {db:null, isInited:false};
        }
        var instance = state.instance[_dbName];
        
        if (instance.isInited) {
            state._safeCallback('vi', initFinishCallback, state._stringToC(_dbName));
            return;
        }

        try {
            // 使用兼容的方式获取 indexedDB 引用
            var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
            if (!indexedDB) {
                console.error('IndexedDB is not supported in this browser.');
                return;
            }

            var request = indexedDB.open(_dbName, version);

            request.onerror = function (event) {
                console.error("IndexedDB open error:", event.target.error);
            };

            request.onupgradeneeded = function (event) {
                var db = event.target.result;
                // 创建对象存储空间
                if (!db.objectStoreNames.contains('data_kv')) {
                    //唯一键值对的字符串表
                    db.createObjectStore('data_kv', { keyPath: 'key' });
                }
                // 创建自定义表
                if(_storesJson){
                    var storesArr = JSON.parse(_storesJson);
                    for(var i=0; i<storesArr.length; i++){
                        var storeConfig = storesArr[i];
                        var storeConfig_storeName = storeConfig['name'];
                        var storeConfig_columnsArr = storeConfig['columns'];
                        var store = db.createObjectStore(storeConfig_storeName, { keyPath: 'id', autoIncrement: true }); //唯一索引
                        for(var j=0; j<storeConfig_columnsArr.length; j++){
                            store.createIndex(storeConfig_columnsArr[j] + '_idx', storeConfig_columnsArr[j], { unique: false }); //可重复索引，增加查询速度，其他字段随时加无需声明
                        }
                        store.createIndex('timestamp_idx', 'timestamp', { unique: false }); //可重复索引，增加查询速度，其他字段随时加无需声明
                    }
                }
                console.log("IndexedDB object stores created.");
            };

            request.onsuccess = function (event) {
                state.instance[_dbName].db = event.target.result;
                state.instance[_dbName].isInited = true;
                state._safeCallback('vi', initFinishCallback, state._stringToC(_dbName));
                console.log("IndexedDB opened successfully:", _dbName);
            };

        } catch (e) {
            console.error("IndexedDB initialization failed:", e);
        }
    },
    
    IndexedDB_SetKeyValue: function (dbName, key, stringValue, binaryValue, size) {
        var state = Module.IndexedDBPlugin;
        var instance = state.instance[UTF8ToString(dbName)];

        var _key = UTF8ToString(key);
        var _stringValue = stringValue ? UTF8ToString(stringValue) : null;
        var isBinary = binaryValue ? true : false;

        try {
            var transaction = instance.db.transaction(['data_kv'], 'readwrite');
            var store = transaction.objectStore('data_kv');

            var blob = null;
            if(isBinary){
                var data = new Uint8Array(size);
                for (var i = 0; i < size; i++) {
                    data[i] = HEAPU8[binaryValue + i];
                }
                blob = new Blob([data], { type: 'application/octet-stream' });
            }
            var item = {
                key: _key,
                value: isBinary ? blob : _stringValue,
                isBinary: isBinary,
                timestamp: Date.now()
            };
            var request = store.put(item);

            request.onsuccess = function (event) {
                console.log("Stored successfully:", key, (isBinary ? size : _stringValue));
            };
            request.onerror = function (event) {
                console.error("Storing fail:", event.target.error);
            };
        } catch (e) {
            console.error("Exception in IndexedDB_SetKeyValue:", e);
        }
    },

    IndexedDB_GetKeyValue: function (dbName, key, stringCallbackFunction, binaryCallbackFunction) {
        var state = Module.IndexedDBPlugin;
        var _dbName = UTF8ToString(dbName);
        var instance = state.instance[_dbName];
        var isString = stringCallbackFunction;

        var _key = UTF8ToString(key);

        try {
            if (!instance.db.objectStoreNames.contains('data_kv')) {
                if(isString){
                    state._safeCallback('vii', stringCallbackFunction, state._stringToC(_dbName), 0);
                }else{
                    state._safeCallback('viii', binaryCallbackFunction, state._stringToC(_dbName), 0, 0);
                }
                return;
            }
        
            var transaction = instance.db.transaction(['data_kv'], 'readonly');
            var store = transaction.objectStore('data_kv');
            var request = store.get(_key);

            request.onsuccess = function (event) {
                var item = request.result;
                if (item && item.value) {
                    if(isString){
                        state._safeCallback('vii', stringCallbackFunction, state._stringToC(_dbName), state._stringToC(item.value));
                    }else{
                        var reader = new FileReader();
                        reader.onload = function () {
                            var arrayBuffer = reader.result;
                            var uint8Array = new Uint8Array(arrayBuffer);
                            // 分配内存并复制数据
                            var dataPtr = _malloc(uint8Array.length);
                            HEAPU8.set(uint8Array, dataPtr);
                            state._safeCallback('viii', binaryCallbackFunction, state._stringToC(_dbName), dataPtr, uint8Array.length);
                        };
                        reader.readAsArrayBuffer(item.value);
                    }
                } else {
                    if(isString){
                        state._safeCallback('vii', stringCallbackFunction, state._stringToC(_dbName), 0);
                    }else{
                        state._safeCallback('viii', binaryCallbackFunction, state._stringToC(_dbName), 0, 0);
                    }
                }
            };
            request.onerror = function (event) {
                console.error("Error loading data:", event.target.error);
                if(isString){
                    state._safeCallback('vii', stringCallbackFunction, state._stringToC(_dbName), 0);
                }else{
                    state._safeCallback('viii', binaryCallbackFunction, state._stringToC(_dbName), 0, 0);
                }
            };
        } catch (e) {
            console.error("Exception in LoadBinary:", e);
            if(isString){
                state._safeCallback('vii', stringCallbackFunction, state._stringToC(_dbName), 0);
            }else{
                state._safeCallback('viii', binaryCallbackFunction, state._stringToC(_dbName), 0, 0);
            }
        }
    },
    
    // 删除1条数据
    IndexedDB_DeleteKey: function (dbName, key) {
        var state = Module.IndexedDBPlugin;
        var instance = state.instance[UTF8ToString(dbName)];
    
        var _key = UTF8ToString(key);

        try {
            var transaction = instance.db.transaction(['data_kv'], 'readwrite');
            var store = transaction.objectStore('data_kv');
            var request = store.delete(_key);

            request.onsuccess = function (event) {
                console.log("Data deleted successfully:", _key);
            };
            request.onerror = function (event) {
                console.error("Error deleting data:", event.target.error);
            };
        } catch (e) {
            console.error("Exception in DeleteData:", e);
        }
    },

    // 添加字符串记录
    IndexedDB_InsertToList: function (dbName, storeName, columnsArrJson, valuesArrJson) {
        var state = Module.IndexedDBPlugin;
        var instance = state.instance[UTF8ToString(dbName)];

        var _storeName = UTF8ToString(storeName);
        var _columns = UTF8ToString(columnsArrJson);
        var _values = UTF8ToString(valuesArrJson);

        try {
            var transaction = instance.db.transaction([_storeName], 'readwrite');
            var store = transaction.objectStore(_storeName);

            var item = {
                timestamp: Date.now()
            };
            
            var _columnArr = JSON.parse(_columns);
            var _valuesArr = JSON.parse(_values);
            for(var i=0; i<_columnArr.length; i++){
                item[_columnArr[i]] = _valuesArr[i];
            }

            var request = store.put(item);

            request.onsuccess = function (event) {
                console.log("String stored successfully:");
            };
            request.onerror = function (event) {
                console.error("Error storing string:", event.target.error);
            };
        } catch (e) {
            console.error("Exception in StoreString:", e);
        }
    },
    
    // 修改字符串记录
    IndexedDB_UpdateListById: function (dbName, storeName, id, columnsArrJson, valuesArrJson) {
        var state = Module.IndexedDBPlugin;
        var instance = state.instance[UTF8ToString(dbName)];

        var _storeName = UTF8ToString(storeName);
        var _id = parseInt(UTF8ToString(id));
        var _columns = UTF8ToString(columnsArrJson);
        var _values = UTF8ToString(valuesArrJson);

        try {
            var transaction = instance.db.transaction([_storeName], 'readwrite');
            var store = transaction.objectStore(_storeName);
            
            // 先查询现有记录
            var getRequest = store.get(_id);
            getRequest.onsuccess = function (event) {
                var existingItem = getRequest.result;
                if (!existingItem) {
                    console.error("Record not found for ID:", _id);
                    return;
                }
                // 更新content和timestamp，保留其他字段
                var updatedItem = {
                    id: _id,
                    timestamp: Date.now() // 更新时间戳
                };
                
                var _columnArr = JSON.parse(_columns);
                var _valuesArr = JSON.parse(_values);
                for(var i=0; i<_columnArr.length; i++){
                    updatedItem[_columnArr[i]] = _valuesArr[i];
                }
    
                var updateRequest = store.put(updatedItem);
                updateRequest.onsuccess = function (event) {
                    console.log("String updated successfully. ID:", _id);
                };
                updateRequest.onerror = function (event) {
                    console.error("Error updating string:", event.target.error);
                };
            };
    
            getRequest.onerror = function (event) {
                console.error("Error finding record:", event.target.error);
            };
        } catch (e) {
            console.error("Exception in StoreString:", e);
        }
    },

    // 读取字符串
    IndexedDB_SelectList: function (dbName, storeName, searchColumn, searchValue, searchValueType, callbackFunction) {
        var state = Module.IndexedDBPlugin;
        var _dbName = UTF8ToString(dbName);
        var instance = state.instance[_dbName];

        var _storeName = UTF8ToString(storeName);
        var _searchColumn = UTF8ToString(searchColumn);
        var _searchValue = UTF8ToString(searchValue);
        var _searchValueType = UTF8ToString(searchValueType);
        if(_searchValueType === 'int'){
            _searchValue = parseInt(_searchValue);
        }

        try {
            if (!instance.db.objectStoreNames.contains(_storeName)) {
                state._safeCallback('vii', callbackFunction, state._stringToC(_dbName), 0);
                return;
            }
        
            var transaction = instance.db.transaction([_storeName], 'readonly');
            var store = transaction.objectStore(_storeName);
            var request = null;
            if (_searchColumn === 'id') {
                request = store.get(_searchValue);
            } else {
                var index = store.index(_searchColumn + '_idx');
                request = index.getAll(_searchValue);
            }

            request.onsuccess = function (event) {
                var results = request.result;
                if (!results || (Array.isArray(results) && results.length === 0)) {
                    state._safeCallback('vii', callbackFunction, state._stringToC(_dbName), 0); // 空结果
                    return;
                }
                var items = Array.isArray(results) ? results : [results];
                if (items.length === 0) {
                    state._safeCallback('vii', callbackFunction, state._stringToC(_dbName), 0);
                    return;
                }
                // 将字符串数组转换为C可用的格式
                var itemsJson = JSON.stringify(items);
                state._safeCallback('vii', callbackFunction, state._stringToC(_dbName), state._stringToC(itemsJson));
            };

            request.onerror = function (event) {
                console.error("Error loading string:", event.target.error);
                state._safeCallback('vii', callbackFunction, state._stringToC(_dbName), 0);
            };

        } catch (e) {
            console.error("Exception in LoadString:", e);
            state._safeCallback('vii', callbackFunction, state._stringToC(_dbName), 0);
        }
    },
    
    // 删除多条数据
    IndexedDB_DeleteListByColumn: function (dbName, storeName, column, value) {
        var state = Module.IndexedDBPlugin;
        var instance = state.instance[UTF8ToString(dbName)];
 
        var _storeName = UTF8ToString(storeName);
        var _column = UTF8ToString(column);
        var _value = UTF8ToString(value);
        
        var transaction = instance.db.transaction([_storeName], 'readwrite');
        var store = transaction.objectStore(_storeName);
        
        try {
            if(_column === 'id'){
                var _id = parseInt(_value);
                var request = store.delete(_id);
                request.onsuccess = function (event) {
                    console.log("Data deleted successfully:", _id);
                };
                request.onerror = function (event) {
                    console.error("Error deleting data:", event.target.error);
                };
                return;
            }
            
            //按条件删除
            var index = store.index(_column + '_idx');
            var getKeysRequest = index.getAllKeys(_value);
            getKeysRequest.onsuccess = function (event) {
                var keys = getKeysRequest.result;
                if (!keys || keys.length === 0) {
                    console.log("No records found for column:", _value);
                    return;
                }
                var deleteCount = 0;
                var errorCount = 0;
                keys.forEach(function(key) {
                    var deleteRequest = store.delete(key);
                    deleteRequest.onsuccess = function() {
                        deleteCount++;
                    };
                    deleteRequest.onerror = function() {
                        errorCount++;
                        console.error("Error deleting record with key:", key);
                    };
                });
                transaction.oncomplete = function() {
                    console.log("Deleted", deleteCount, "records for column:", _value);
                    if (errorCount > 0) {
                        console.error("Failed to delete", errorCount, "records");
                    }
                };
                transaction.onerror = function(event) {
                    console.error("Transaction error:", event.target.error);
                };
            }
            getKeysRequest.onerror = function (event) {
                console.error("Error getting keys for column:", _value, event.target.error);
            };
        } catch (e) {
            console.error("Exception in DeleteData:", e);
        }
    },
    
    // 清空数据
    IndexedDB_ClearList: function (dbName, storeName) {
        var state = Module.IndexedDBPlugin;
        var instance = state.instance[UTF8ToString(dbName)];
        
        var _storeName = UTF8ToString(storeName);
 
        var transaction = instance.db.transaction([_storeName], 'readwrite');
        var store = transaction.objectStore(_storeName);
        
        try {
            var request = store.clear();
            request.onsuccess = function (event) {
                console.log("All records cleared from list store");
            };
            request.onerror = function (event) {
                console.error("Error clearing table:", event.target.error);
            };
        } catch (e) {
            console.error("Exception in DeleteData:", e);
        }
    },
    
    // 显式同步数据到 IndexedDB
    IndexedDB_SyncFS: function () {
        var state = Module.IndexedDBPlugin;
        state._safeSyncFS(function(err) {
            if (err) {
                console.error("SyncFS failed:", err);
            }
        });
    },
});